package com.hmdp.lock;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @description TODO
 * @author sats@jz
 * @date 2024年10月24日 14:19
 */
public class LuaRedisLock implements ILock{
    private StringRedisTemplate stringRedisTemplate;
    private String name;
    private final static String KEY_PREFIX = "lock:";
    private final static String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    // 释放锁的脚本,通过文件加载
    private static final DefaultRedisScript<Long> SECUNLOCK_SCRIPT;
    static {
        SECUNLOCK_SCRIPT = new DefaultRedisScript<>();
        SECUNLOCK_SCRIPT.setLocation(new ClassPathResource("/lua/secUnlock.lua"));
        SECUNLOCK_SCRIPT.setResultType(Long.class);
    }



    public LuaRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean tryLock(long timeoutSec) {
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        Boolean isLock = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        // 防止自动拆箱的空指针
        return Boolean.TRUE.equals(isLock);
    }

    @Override
    public void unlock() {
        // 判断标识是否一致
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 调用lua脚本, 满足了原子性
        stringRedisTemplate.execute(
                SECUNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                threadId);
    }
}
